package fr.alma.music;


import static fr.alma.domo.music.PositionService.POSITION_WC;
import static org.junit.Assert.assertTrue;

import org.apache.tuscany.sca.node.Contribution;
import org.apache.tuscany.sca.node.ContributionLocationHelper;
import org.apache.tuscany.sca.node.Node;
import org.apache.tuscany.sca.node.NodeFactory;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import fr.alma.domo.music.MusicPlayerSCM;
import fr.alma.domo.music.PositionService;
import fr.alma.domo.music.rc.HP;
import fr.alma.domo.music.rc.Player;
import fr.alma.domo.svc.AdaptationHandler;
import fr.alma.domo.svc.SelectionAndDiscoveryImpl;
import fr.alma.domo.util.Log;

public class Scenario3{

	private static Node node1;
	private static MusicPlayerSCM musicPlayerService;
	private static PositionService positionService;
	private static AdaptationHandler adaptationHandler;
	private static String clientId;
	private static Player player;
	private static HP hp1,hp2;
	private static Thread adaptationThread;
	
	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		String location1 = ContributionLocationHelper.getContributionLocation(MusicPlayerSCM.class);
		String location2 = ContributionLocationHelper.getContributionLocation(SelectionAndDiscoveryImpl.class);
		node1 = NodeFactory.newInstance().createNode(new Contribution("c1", location1)
				,new Contribution("c2", location2));
		node1.start();

		
		musicPlayerService = node1.getService(MusicPlayerSCM.class,"MusicPlayerSCMComponent");
		positionService = node1.getService(PositionService.class,"PositionServiceComponent");
		
		//Demarrage du gestionnaire d'adaptation
		adaptationHandler = node1.getService(AdaptationHandler.class, "AdaptationHandlerComponent");
		adaptationThread = new Thread(new Runnable(){

			@Override
			public void run() {
				adaptationHandler.startAdaptationLoop();
			}
			
		});
		adaptationThread.setDaemon(true);
		adaptationThread.start();
		
		clientId = positionService.getClientId("Dr Strange");
		
		player = new Player();
		hp1 = new HP(POSITION_WC);
		hp2 = new HP(POSITION_WC);
		
		player.startService();
		hp1.startService();
		hp2.startService();
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception {
		node1.stop();
		player.stopService();
		hp1.stopService();
		hp2.stopService();
		node1=null;
		adaptationHandler=null;
		musicPlayerService=null;
		positionService=null;
		clientId=null;
		player=null;
		hp1=hp2=null;
		adaptationThread=null;
	}

	@Test public void testPlayAndHPSwitch(){
		Log.i(getClass().getName(), "================ TEST PLAY AND HP SWITCH");
		musicPlayerService.play(clientId,player, hp1);
		hp1.setWorking(false);
		//si tout marche hp1 a été remplacer par hp2
		assertTrue(hp2.isBusy());
		Log.i(getClass().getName(), "*****************************************");
		Log.i(getClass().getName(), "");
	}
}
